import { getProductCategoryPartAll } from "@/api/modules/carType";

export const useUtile = () => {
  /**
   * 提交选项数据
   */
  const changeHandlerOptions = (val: any[], item: any, selectList: any) => {
    item.contentOptional = []; // 选配
    item.chooseOptional = []; // 标配
    val.forEach((itm: String) => {
      const prefix = itm.split("--")[0];
      const value = itm.split("--")[1];
      const itemOrigin = selectList[item.type === 4 ? item.value : item.typeId].find(iem => iem.id == itm);
      if (itemOrigin) {
        if (prefix === "标配") {
          item.chooseOptional.push({
            sourceId: value,
            sourceName: itemOrigin.name.split("--")[1]
          });
        } else {
          item.contentOptional.push({
            sourceId: value,
            sourceName: itemOrigin.name.split("--")[1]
          });
        }
      }
    });
  };
  /**
   * 生成选项数据
   */
  const changeOptionsData = (res: any, excluded?: any[]) => {
    try {
      Object.keys(res)
        .filter(item => !excluded?.includes(item))
        .forEach(key => {
          const bp = res[key].map((item: any) => {
            return {
              ...item,
              name: `标配--` + item.name,
              id: `标配--` + item.id
            };
          });
          const xp = res[key].map((item: any) => {
            return {
              ...item,
              name: `选配--` + item.name,
              id: `选配--` + item.id
            };
          });
          res[key] = [...bp, ...xp];
        });
      return res;
    } catch (error) {
      console.log(error);
    }
  };
  const transformDataRes = (data: any) => {
    data = data || [];
    data.forEach((item: any) => {
      const content: any[] = [];
      item.content &&
        item.content.forEach(itm => {
          content.push(`标配--${itm.sourceId}`);
        });
      item.contentOptional &&
        item.contentOptional.forEach(itm => {
          content.push(`选配--${itm.sourceId}`);
        });
      item.chooseOptional = JSON.parse(JSON.stringify(item.content));
      item.content = content;
    });
    return data;
  };
  const transformDataReq = (data: any) => {
    data = JSON.parse(JSON.stringify(data));
    data.propertyList.forEach((item: any) => {
      item.content = item.chooseOptional;
      delete item.chooseOptional;
    });
    return data;
  };

  const fittingsFn = async (typeId: string) => {
    const { data } = await getProductCategoryPartAll(
      {
        typeId
      },
      { noLoading: true }
    );
    const obj: any = {};
    obj[typeId] = data;
    return obj;
  };

  const isBp = (item: string) => {
    return item.split("--")[0] === "标配";
  };
  const isXp = (item: string) => {
    return item.split("--")[0] === "选配";
  };
  return { changeHandlerOptions, changeOptionsData, transformDataReq, transformDataRes, fittingsFn, isBp, isXp };
};
